import 'package:flutter/material.dart';
import 'dart:math' as math;

class CompassControl extends StatelessWidget {
  final double pitch;
  final double roll;
  final VoidCallback onCalibrate;
  final bool isCalibrating;

  const CompassControl({
    super.key,
    required this.pitch,
    required this.roll,
    required this.onCalibrate,
    required this.isCalibrating,
  });

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    final compassSize = screenSize.height * 0.5; // 罗盘大小为屏幕高度的50%
    final buttonHeight = screenSize.height * 0.06; // 按钮高度为屏幕高度的6%
    final spacing = screenSize.height * 0.02; // 间距为屏幕高度的2%
    final fontSize = screenSize.height * 0.02; // 字体大小为屏幕高度的2%

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 校准按钮
        SizedBox(
          height: buttonHeight,
          child: ElevatedButton.icon(
            onPressed: isCalibrating ? null : onCalibrate,
            icon: Icon(Icons.settings_backup_restore, size: buttonHeight * 0.6),
            label: Text(
              isCalibrating ? '校准中...' : '校准传感器',
              style: TextStyle(fontSize: fontSize),
            ),
            style: ElevatedButton.styleFrom(
              backgroundColor: Theme.of(context).colorScheme.secondary,
              foregroundColor: Theme.of(context).colorScheme.onSecondary,
              padding: EdgeInsets.symmetric(horizontal: spacing * 2),
            ),
          ),
        ),
        SizedBox(height: spacing),
        // 罗盘控制
        SizedBox(
          width: compassSize,
          height: compassSize,
          child: Container(
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Theme.of(context).colorScheme.surfaceVariant,
              border: Border.all(
                color: Theme.of(context).colorScheme.primary,
                width: 2,
              ),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: CustomPaint(
              painter: CompassPainter(
                pitch: pitch,
                roll: roll,
                theme: Theme.of(context),
              ),
            ),
          ),
        ),
        SizedBox(height: spacing),
        // 倾斜角度显示
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _buildAngleIndicator(context, '俯仰', pitch, fontSize),
            SizedBox(width: spacing * 2),
            _buildAngleIndicator(context, '滚转', roll, fontSize),
          ],
        ),
      ],
    );
  }

  Widget _buildAngleIndicator(BuildContext context, String label, double value, double fontSize) {
    return Column(
      children: [
        Text(
          label,
          style: TextStyle(fontSize: fontSize),
        ),
        const SizedBox(height: 4),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          decoration: BoxDecoration(
            color: Theme.of(context).colorScheme.primaryContainer,
            borderRadius: BorderRadius.circular(16),
          ),
          child: Text(
            '${(value * 90).toStringAsFixed(1)}°',
            style: TextStyle(
              fontSize: fontSize,
              fontWeight: FontWeight.bold,
              color: Theme.of(context).colorScheme.onPrimaryContainer,
            ),
          ),
        ),
      ],
    );
  }
}

class CompassPainter extends CustomPainter {
  final double pitch;
  final double roll;
  final ThemeData theme;

  CompassPainter({
    required this.pitch,
    required this.roll,
    required this.theme,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = math.min(size.width, size.height) / 2;
    final fontSize = radius * 0.08; // 字体大小为半径的8%

    // 绘制罗盘背景
    final backgroundPaint = Paint()
      ..color = theme.colorScheme.surface
      ..style = PaintingStyle.fill;
    canvas.drawCircle(center, radius * 0.9, backgroundPaint);

    // 绘制罗盘刻度
    final tickPaint = Paint()
      ..color = theme.colorScheme.onSurface.withOpacity(0.5)
      ..strokeWidth = radius * 0.004
      ..style = PaintingStyle.stroke;

    for (int i = 0; i < 360; i += 10) {
      final angle = i * math.pi / 180;
      final outerRadius = i % 30 == 0 ? radius * 0.85 : radius * 0.88;
      final innerRadius = radius * 0.8;
      
      final outerPoint = Offset(
        center.dx + outerRadius * math.cos(angle),
        center.dy + outerRadius * math.sin(angle),
      );
      
      final innerPoint = Offset(
        center.dx + innerRadius * math.cos(angle),
        center.dy + innerRadius * math.sin(angle),
      );
      
      canvas.drawLine(innerPoint, outerPoint, tickPaint);
      
      if (i % 30 == 0) {
        final textPainter = TextPainter(
          text: TextSpan(
            text: (i ~/ 10).toString(),
            style: TextStyle(
              color: theme.colorScheme.onSurface.withOpacity(0.7),
              fontSize: fontSize * 0.6,
            ),
          ),
          textDirection: TextDirection.ltr,
        );
        
        textPainter.layout();
        
        final textPoint = Offset(
          center.dx + radius * 0.7 * math.cos(angle) - textPainter.width / 2,
          center.dy + radius * 0.7 * math.sin(angle) - textPainter.height / 2,
        );
        
        textPainter.paint(canvas, textPoint);
      }
    }

    // 绘制方向标记 (N, E, S, W)
    final directionTextStyle = TextStyle(
      color: theme.colorScheme.onSurface,
      fontSize: fontSize,
      fontWeight: FontWeight.bold,
    );
    
    _drawDirectionText(canvas, center, radius * 0.6, 0, 'N', directionTextStyle);
    _drawDirectionText(canvas, center, radius * 0.6, 90, 'E', directionTextStyle);
    _drawDirectionText(canvas, center, radius * 0.6, 180, 'S', directionTextStyle);
    _drawDirectionText(canvas, center, radius * 0.6, 270, 'W', directionTextStyle);

    // 绘制水平线
    final horizonPaint = Paint()
      ..color = theme.colorScheme.primary
      ..strokeWidth = radius * 0.008
      ..style = PaintingStyle.stroke;

    // 应用倾斜角度
    canvas.save();
    canvas.translate(center.dx, center.dy);
    canvas.rotate(roll * math.pi / 2); // 滚转角度
    
    // 绘制水平线
    canvas.drawLine(
      Offset(-radius * 0.7, pitch * radius * 0.7), // 俯仰角度
      Offset(radius * 0.7, pitch * radius * 0.7),
      horizonPaint,
    );
    
    // 绘制飞机指示器
    final planePaint = Paint()
      ..color = theme.colorScheme.primary
      ..style = PaintingStyle.fill;
    
    // 飞机形状
    final planeShape = Path()
      ..moveTo(0, -radius * 0.15) // 机头
      ..lineTo(radius * 0.1, 0) // 右翼
      ..lineTo(0, radius * 0.05) // 机尾
      ..lineTo(-radius * 0.1, 0) // 左翼
      ..close();
    
    canvas.drawPath(planeShape, planePaint);
    
    // 绘制飞机边框
    final planeBorderPaint = Paint()
      ..color = theme.colorScheme.onPrimary
      ..strokeWidth = radius * 0.004
      ..style = PaintingStyle.stroke;
    
    canvas.drawPath(planeShape, planeBorderPaint);
    
    canvas.restore();
  }

  void _drawDirectionText(Canvas canvas, Offset center, double distance, double angleDegrees, String text, TextStyle style) {
    final angle = angleDegrees * math.pi / 180;
    final textPainter = TextPainter(
      text: TextSpan(text: text, style: style),
      textDirection: TextDirection.ltr,
    );
    
    textPainter.layout();
    
    final textPoint = Offset(
      center.dx + distance * math.sin(angle) - textPainter.width / 2,
      center.dy - distance * math.cos(angle) - textPainter.height / 2,
    );
    
    textPainter.paint(canvas, textPoint);
  }

  @override
  bool shouldRepaint(CompassPainter oldDelegate) {
    return pitch != oldDelegate.pitch || roll != oldDelegate.roll;
  }
} 